package cn.kduck.assembler.security.authentication;

import cn.kduck.security.handler.LoginFailHandler;
import cn.kduck.security.handler.LoginSuccessHandler;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class PhoneNumAuthenticationFilter extends AbstractAuthenticationProcessingFilter implements ApplicationContextAware {

    public static final String SPRING_SECURITY_FORM_PHONE_NUM_KEY = "phoneNum";

    public static final String SPRING_SECURITY_FORM_CAPTCHA_CODE_KEY = "captchaCode";

    private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/phone/login",
            "POST");

    private String phoneNumParameter = SPRING_SECURITY_FORM_PHONE_NUM_KEY;

    private String captchaCodeParameter = SPRING_SECURITY_FORM_CAPTCHA_CODE_KEY;

//    @Autowired
//    private UserService userService;
//
//    @Autowired
//    private AccountService accountService;



    public PhoneNumAuthenticationFilter(){
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String phoneNum = request.getParameter(phoneNumParameter);
        String captchaCode = request.getParameter(captchaCodeParameter);

//        User user = userService.getUserByPhone(phoneNum);
//        Account account = accountService.getAccountByUserId(user.getUserId());

        PhoneNumAuthenticationToken authenticatedToken = new PhoneNumAuthenticationToken(phoneNum, captchaCode);
        authenticatedToken.setCaptchaCode(captchaCode);

        return this.getAuthenticationManager().authenticate(authenticatedToken);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        LoginSuccessHandler loginSuccessHandler = applicationContext.getBean(LoginSuccessHandler.class);
        LoginFailHandler loginFailHandler = applicationContext.getBean(LoginFailHandler.class);
        super.setAuthenticationSuccessHandler(loginSuccessHandler);
        super.setAuthenticationFailureHandler(loginFailHandler);
    }
}
